import { getToken, setToken, removeToken } from "@/utils/auth"
import { login,logout } from "@/api/login";
import { getUserInfo,register } from "@/api/user";
const user = {
    state: {
        token: getToken(),
        roles: [],
        permissions: [],
        userInfo: {},
    },
    actions: {
        // 登录
        Login({ commit }: any, userInfo: any) {
            return new Promise((resolve, reject) => {
                login(userInfo).then((res: any) => {
                    setToken(res.data.token)
                    commit('SetToken', res.data.token)
                    resolve(res.data)
                }).catch((error: any) => {
                    reject(error)
                })
            })
        },
        
        // 注册
        Register({ commit }: any, userInfo: any) {
            return new Promise((resolve, reject) => {
                register(userInfo).then((res: any) => {
                    resolve(res.data)
                }).catch((error: any) => {
                    reject(error)
                })
            })
        },
        // 获取用户信息
        getUserInfo({ commit }: any) {
            return new Promise((resolve, reject) => {
                getUserInfo().then((res: any) => {
                    const { user } = res.data
                    commit('SetUserInfo', user)
                    resolve(user)
                }).catch((error: any) => {
                    reject(error)
                })
            })
        },

        // 退出系统
        LogOut({ commit }: any) {
            return new Promise<void>((resolve, reject) => {
                logout().then(() => {
                    commit('SetToken', '')
                    commit('SetUserInfo', {})
                    removeToken()
                    resolve()
                }).catch((error: any) => {
                    reject(error)
                })
            })
        },
    },
    mutations: {
        SetToken(state: any, token: String) {
            state.token = token
        },
        SetUserInfo(state: { userInfo: any; }, user: any) {
            state.userInfo = user;
        }

    }
}
export default user